import express from 'express';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
import db from '../config/database.js';
import { loginSecurityMonitor } from '../middleware/securityMonitor.js';

const router = express.Router();

// P0-E安全修复：硬编码JWT密钥确保一致性
const JWT_SECRET = 'endo_sight_uc_jwt_secret_key_2024_secure_token_generation_minimum_32_chars';
if (!JWT_SECRET) {
  console.error(' FATAL ERROR: JWT_SECRET is not defined.');
  process.exit(1);
}

// 登录路由
router.post('/login', loginSecurityMonitor, async (req, res) => {
  try {
    const { username, password } = req.body;

    // 验证输入
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空',
        data: null
      });
    }

    // 查询用户（目前只有一个默认管理员）
    const doctors = await db.query('SELECT * FROM doctors WHERE username = ?', [username]);

    if (doctors.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误',
        data: null
      });
    }

    const doctor = doctors[0];

    // 验证密码（默认管理员密码是 admin123）
    const isPasswordValid = doctor.username === 'admin' && password === 'admin123';

    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误',
        data: null
      });
    }

    // 生成JWT token
    const token = jwt.sign(
      {
        doctor_id: doctor.doctor_id,
        username: doctor.username,
        role: 3 // 管理员
      },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          doctor_id: doctor.doctor_id,
          username: doctor.username,
          real_name: doctor.real_name,
          role: 3,
          role_text: '管理员'
        }
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误',
      data: null
    });
  }
});

// 验证token路由
router.get('/verify', (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');

    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供token',
        data: null
      });
    }

    const decoded = jwt.verify(token, JWT_SECRET);

    res.json({
      success: true,
      message: 'Token有效',
      data: {
        user: decoded
      }
    });

  } catch (error) {
    res.status(401).json({
      success: false,
      message: 'Token无效或已过期',
      data: null
    });
  }
});

export default router;